

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nmb/models/fold.dart';
import 'package:nmb/models/note.dart';

import 'database.dart';

class GlobalService{


  static GlobalService? _instance;

  final dbHelper = Get.find<DatabaseService>();

  // 私有构造函数，初始化一次
  GlobalService._internal(){
    loadFold();
    loadNotes();
  }

  loadFold(){
    foldList = [];
    foldList.add(
        Fold(id: '', name: '全部')
    );
    dbHelper.readAllFolds().then((fds){
      foldList.addAll(fds);
      toggleFolderState();
    });
  }

  loadNotes(){
    noteList = [];
    dbHelper.readAllNotes().then((nts){
      noteList = nts;
      toggleNoteState();
    });
  }

  createNote(Note note) async {
    await dbHelper.createNote(note);
    loadNotes();
  }

  updateNote(Note note) async {
    await dbHelper.updateNote(note);
    loadNotes();
  }

  addFold(Fold f) async {
    await dbHelper.createFold(f);
    loadFold();
  }

  updateFold(Fold f) async {
    await dbHelper.updateFold(f);
    loadFold();
  }

  delFold(List<String> ids) async{
    // 删除文件夹
    await dbHelper.delFold(ids);
    loadFold();
    // 重置笔记文件夹
    List<Note> shouldUpdate = [];
    for (var n in noteList) {
      if(ids.contains(n.foldId)){
        n.foldId = '';
        shouldUpdate.add(n);
      }
    }
    if(shouldUpdate.isNotEmpty){
      await dbHelper.updateNotes(shouldUpdate);
      toggleNoteState();
    }
  }

  final ValueNotifier<bool> noteChanged = ValueNotifier(false);

  final ValueNotifier<bool> folderChanged = ValueNotifier(false);

  final ValueNotifier<bool> showSearch = ValueNotifier(false);

  late List<Note> noteList;

  late List<Fold> foldList;

  // 工厂构造函数返回唯一实例
  factory GlobalService() {
    _instance ??= GlobalService._internal();
    return _instance!;
  }

  toggleNoteState(){
    noteChanged.value=!noteChanged.value;
  }

  toggleFolderState(){
    folderChanged.value = !folderChanged.value;
  }

  toggleSearchState(){
    showSearch.value = !showSearch.value;
  }
}